import os
import base64
from amzqr import amzqr

TEMPLATE = open("/code/index.html").read()
SOURCE = "/code/assets/pic.png"
TARGET = "/code/assets/pic_qrcode.png"

def handler(environ, start_response):
    query_string = environ.get('QUERY_STRING', '')
    print(f"query_string = {query_string}")
    query_components = query_string.split('&')
    data = None
    params = dict()
    for component in query_components:
        if component != "":
            key, value = component.split('=')
            params[key] = value
    data = params.get('data')
    if data is None:
        data = "hello cf"

    version, level, qr_name = amzqr.run(
        data,
        version=1,
        level='H',
        picture=SOURCE,
        colorized=False,
        contrast=1.0,
        brightness=1.0,
        save_name=TARGET,
        save_dir=os.getcwd()
    )
    with open(TARGET, "rb") as file:
        target_file_data = file.read()
    base64_file_data = base64.b64encode(target_file_data)
    base64_file_string = base64_file_data.decode('utf-8')

    status = '200 OK'
    response_headers = [('Content-type', 'text/html')]
    start_response(status, response_headers)
    return [TEMPLATE.replace("{cf-base64-img}", base64_file_string)]
